﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sobiens.Connector.Admin.DAL;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Json;
using Sobiens.Connector.Admin.BLL;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace Sobiens.Connector.Admin.UI
{
    internal class ConnectorAdminPresenter
    {
        private const String START_TOKEN = "BEGINSOBIENSXML";
        private const String END_TOKEN = "ENDSOBIENSXML";
        
        private IConnectorAdminView _view;
        
        private ConnectorAdminModel _model;

        public ConnectorAdminPresenter(IConnectorAdminView view)
        {
            _view = view;
        }

        internal void Init()
        {
            _view.PopulateFromModel(GetModel());
        }

        private ConnectorAdminModel GetModel()
        {
            if (_model == null)
            {
                ConnectorAdminModelAssembler assembler = new ConnectorAdminModelAssembler();
                _model = assembler.GetModelForConfiguration(_view.SelectedConfigurationId);
            }
            return _model;
        }


        internal void LoadCurrentConfiguration()
        {
            Init();
        }

        internal void SaveCurrentConfigurationData(String configId, String appConfigurationJSONData)
        {
            Sobiens.Connectors.Entities.Settings.AppConfiguration appConfig = Sobiens.Connectors.Entities.Settings.AppConfiguration.CreateFromJSON(appConfigurationJSONData);
            appConfig.ProcessDeletedElements();
            appConfig.ProcessNewElements();
            String xmlData = appConfig.GetXML();
            ConfigurationList configList = new ConfigurationList();
            configList.UpdateItem(new Guid(configId), xmlData);
           _view.PopulateFromModel(GetModel());
        }

        internal string GetConfigUrlXml(String configurationGuid)
        {
            ConfigurationList configList = new ConfigurationList();

            SPListItem item = configList.GetItem(new Guid(configurationGuid));
            String lastVersion = item.Versions[0].VersionLabel;

            String xml = item[ConfigurationList.FIELDS.DATA].ToString().Trim();
            XDocument xDoc = XDocument.Parse(xml);
            xDoc.Root.Add(new XElement("Version", lastVersion));

            return String.Format("{0}{1}{2}", START_TOKEN, xDoc.ToString(), END_TOKEN);
        }
    }
}
